package cn.itcast.service;

import cn.itcast.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: IpCountService
 * Description:
 * Date: 2023/03/23 PM 10:36:29
 * <p>
 * project: springboot
 * package: cn.itcast.service
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class IpCountService {

    private final Map<String, Integer> ipCountMap = new HashMap<>();

    /**
     * 当前的 request 对象的注入工作由使用当前 starter 工程提供自动装配
     */
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private IpProperties ipProperties;

    public void count() {
        // 每次调用当前操作，就记录当前访问 IP, 然后累加访问次数
        // 1.获取当前操作的 IP 地址
        String ip = httpServletRequest.getRemoteAddr();
        // 2.根据 IP 地址从 Map 取值, 并递增
        ipCountMap.merge(ip, 1, Integer::sum);
    }

    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?")
    public void print() {
        System.out.println("          IP访问监控");
        if (ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())) {
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.printf("|%18s  |%5d |%n", key, value);
            }
            System.out.println("+--------------------+-------+");
        } else if (ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())) {
            System.out.println("+-----ip-address-----+--num--+");
            for (String key : ipCountMap.keySet()) {
                System.out.printf("|%18s  |%n", key);
            }
            System.out.println("+--------------------+-------+");
        }

        if (ipProperties.getCycleReset()) {
            ipCountMap.clear();
        }
    }

    public static void main(String[] args) {
        new IpCountService().print();
    }
}
